const { Sequelize } = require("sequelize");
const moment = require('moment');
const { Knowledge, Food, User } = require("../database/index");
const Redis = require("ioredis");
const redis = new Redis();
//修改hgetall
Redis.Command.setReplyTransformer("hgetall", (result) => {
    const arr = [];
    for (let i = 0; i < result.length; i += 2) {
        arr.push({ knowledgeId: result[i], views: result[i + 1] });
    }
    return arr;
});
const timeScript = {
    /** 定时将redis数据更新到数据库*/
    async updateKnowledgeRedisViews() {
        // console.log('每隔一会儿就执行')
        await redis.hgetall('knowledgeviews').then(async (viewobjs) => {
            //批量更新数据库
            if (viewobjs) {
                console.log('redis', viewobjs)
                await Knowledge.bulkCreate(
                    viewobjs,
                    {
                        updateOnDuplicate: ["knowledgeId", 'views'],
                    }
                );

            }
        })
    },
    /** 定时用数据库食物更新redis*/
    async updateFoodRedis() {
        // console.log('每隔一会儿就执行')
        let foods = await Food.findAll({
            attributes: ['foodId', 'foodName', 'unit']
        })
        for (let i = 0; i < foods.length; i++) {
            if (foods[i].unit == null || foods[i].unit == '' || foods[i].unit == " ") {
                foods[i].unit = 0
            }
            await redis.sadd('foodInfos', foods[i].foodName + "#" + foods[i].foodId + "_" + foods[i].unit)
        }

    },
    async updateUserTotalKal() {
        const Op = Sequelize.Op;
        // console.log('每隔一会儿就执行')
        let users = await User.findAll({
            where:{
                type: {
                    [Op.eq]: 1
                  }
            }
        });
        let needUpdatedUsers = []
        for (let i = 0; i < users.length; i++) {
            if(users[i].birthDay){
                const currentAge = moment().diff(moment(users[i].birthDay, "YYYY-MM-DD"), 'years');//现在的年龄
                const registAge = moment(users[i].updatedAt).diff(moment(users[i].birthDay, "YYYY-MM-DD"), 'years');//当时注册的年龄（利用每次的更新时间）
                if (currentAge - registAge > 0) {
                    // console.log(33333333333,currentAge - registAge)
                    //现在的年龄-当时注册的年龄>0,说明长了1岁，需要根据当前年龄计算系数，重新设置totalKcal
                    let xishu = 0
                    if (currentAge >= 10) {
                        xishu = 70
                    } else if (currentAge < 10 && currentAge >= 7) {
                        xishu = 80
                    } else if (currentAge < 7 && currentAge >= 3) {
                        xishu = 90
                    } else {
                        xishu = 100
                    }
                    needUpdatedUsers.push({userId:users[i].userId,totalKcal:1000 + currentAge * xishu,updatedAt:new Date()})
                }
                // console.log(11111111111111,needUpdatedUsers)
            }
        }
        if (needUpdatedUsers.length>0) {
            await User.bulkCreate(
                needUpdatedUsers,
                {
                    updateOnDuplicate: ["userId", 'totalKcal','updatedAt'],
                }
            );
        }

    },
};
module.exports = timeScript;